package com.example.reggie.controller;

import com.example.reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class commonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        log.info("file:{}", file);
        //1.获取文件名
        String fileName = file.getOriginalFilename();
        //2.获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //获取文件前缀
        String prefix = fileName.substring(0, fileName.lastIndexOf("."));
        //3.生成新的文件名
        String newFileName = prefix + UUID.randomUUID() + suffix;

//        获取今年年份 2021
        String year = String.valueOf(java.time.LocalDate.now().getYear());
//        获取今年的第几个月
        String month = String.valueOf(java.time.LocalDate.now().getMonthValue());
//        获取今天是这个月的第几天
        String day = String.valueOf(java.time.LocalDate.now().getDayOfMonth());

        String date = year + "/" + month + "/" + day;

        //4.获取文件上传路径
        String filePath = basePath + date + "/" + newFileName;

//        创建一个文件目录对象
        File fileDir = new File(basePath + date);


//        判断文件目录是否存在
        if (!fileDir.exists()) {
//            如果不存在则创建
            fileDir.mkdirs();
        }

        try {
            //5.创建文件
            File dest = new File(filePath);
            //6.写入文件
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.success("/files/" + date + "/" + newFileName);
    }


    /**
     * 文件下载
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //            输入流 通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
//           从 fileInputStream 获取文件类型
            String contentType = fileInputStream.getChannel().toString();
//            设置响应头
            response.setHeader("Content-Type", contentType);

            //            输出流 通过输出流将文件写回浏览器 再浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
//            关闭流
            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
